package com.example.first.thread;

/**
 * @Author LSQ
 * @Description 两个线程同时对一个共享变量操作
 * @date 2021/11/12 22:35
 * @Version 1.0
 */

public class LearnSynchronized3 {
    // 共享变量
    private static int count = 0;

    private static void increment() {
        count++;
    }

    private static void decrement() {
        count--;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    increment();
                }
            }
        };

        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    decrement();
                }
            }
        };

        Thread thread1 = new Thread(runnable1);
        Thread thread2 = new Thread(runnable2);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        // 结果： 有时候不是0
        System.out.println("result: " + count);
    }

}
